//
//  ZDBShareCircleViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/23.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBShareCircleViewController.h"
#import "ZDBHTMLView.h"
#import "ZDBReceiveCustomAlearView.h"
#import "ZDBBindWXViewController.h"
#import "LLWebViewController.h"
#import "ZDBTastModel.h"
#import "ZDBSubimtTaskViewController.h"

@interface ZDBShareCircleViewController ()
@property (nonatomic,strong)NSString * commentInfo;//评论内容
@property (nonatomic,strong)NSString * shareInfo;//分享内容
@property (nonatomic,strong)NSArray * taskInfoImages;//分享图片
@property (nonatomic,strong)UIScrollView * scrollerView;

@property (nonatomic,strong)UILabel * shareLab;
@property (nonatomic,strong)UIButton  * commentButton;
@property (nonatomic,strong)UILabel  * commentLab;
@property (nonatomic,copy)NSString  * task_ID;
@property (nonatomic,strong)UIView * imgBgView;
@property (nonatomic,strong)NSMutableArray * images;
@property (nonatomic,strong)NSDictionary * taskInfoDicc;
@property (nonatomic,strong)ZDBHTMLView *tableviewHeadView1;
@property (nonatomic,assign)NSInteger state;//状态
@property (nonatomic,assign)NSInteger pag;//状态
@property (nonatomic,strong)NSString * taskMoney;//任务金额
 
@end

@implementation ZDBShareCircleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.taskInfoDicc = [NSDictionary dictionary];
    self.view.backgroundColor = WHITECOLOR;
    self.navigationItem.title = @"任务详情";
    [self.view addSubview:self.scrollerView];
    _images = [NSMutableArray new];
    [self getTaskInfoById];//获取一级任务
    UIButton  * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 26)];
    [button setBackgroundImage:[UIImage imageNamed:@"sharebg"] forState:0];
    [button setTitle:@"分享语" forState:0];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -22 , 0,0)];
    button.titleLabel.font = AutoFont(11);
    [_scrollerView addSubview:button];
    _shareLab = [[UILabel alloc] initWithFrame:CGRectMake(16, button.bottom+10, UIScreenWidth-32, 0)];
    _shareLab.font = AutoFont(10);
    _shareLab.numberOfLines = 0;
     [_scrollerView addSubview:_shareLab];
    
    _commentButton = [[UIButton alloc] initWithFrame:CGRectMake(0, _shareLab.bottom+10, 70, 26)];
    [_commentButton setBackgroundImage:[UIImage imageNamed:@"sharebg"] forState:0];
    [_commentButton setTitle:@"评论语" forState:0];
    _commentButton.titleLabel.font = AutoFont(11);
    [_commentButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -22 , 0,0)];
    [_scrollerView addSubview:_commentButton];
    _commentLab = [[UILabel alloc] initWithFrame:CGRectMake(16, _commentButton.bottom+10, UIScreenWidth-32, 200)];
    _commentLab.font = AutoFont(10);
    _commentLab.numberOfLines = 0;
    [_scrollerView addSubview:_commentLab];
     float image_w = (UIScreenWidth-30)/3 -5;
    _imgBgView = [[UIView alloc] initWithFrame:CGRectMake(15, _commentLab.bottom+10, UIScreenWidth-30, UIScreenWidth-30)];
   
    for(int i = 0; i<3; i++)
    {
        for(int j = 0; j<3; j++)
        {
            UIImageView * imageView = [[UIImageView alloc] init];
            
            // 确定宽、高、X、Y坐标
            CGRect frame;
            frame.size.width = image_w;
            frame.size.height = image_w;
            frame.origin.x = j*(image_w+4);
            frame.origin.y = i*(image_w+4);
            [imageView setFrame:frame];
            [_imgBgView addSubview:imageView];
            [_images addObject:imageView];
        }
       
    }
    [_scrollerView addSubview:_imgBgView];
   _tableviewHeadView1 = [[NSBundle mainBundle] loadNibNamed:@"ZDBHTMLView" owner:self options:nil][1];
    _tableviewHeadView1.frame = CGRectMake(0, _imgBgView.bottom,UIScreenWidth,  750);
    _tableviewHeadView1.centerX =self.scrollerView.centerX;
    [self.scrollerView addSubview:_tableviewHeadView1];
  
          WeakSelf
          [_tableviewHeadView1.receiveBtn add_BtnClickHandler:^(NSInteger tag) {//领取任务
              [weakSelf buttonClick:1];
          }];
          [_tableviewHeadView1.subimtBtn add_BtnClickHandler:^(NSInteger tag) {//提交
                [weakSelf buttonClick:2];
             
          }];
          [_tableviewHeadView1.shareBtn add_BtnClickHandler:^(NSInteger tag) {//复制分享语
              [weakSelf buttonClick:3];
          }];
          [_tableviewHeadView1.duplicateBtn add_BtnClickHandler:^(NSInteger tag) {//复制评论语
              [weakSelf buttonClick:4];
          }];
          [_tableviewHeadView1.savePicturesBtn add_BtnClickHandler:^(NSInteger tag) {//保存图片
               [weakSelf buttonClick:5];
          }];
          [self.lookVideo add_BtnClickHandler:^(NSInteger tag) {//查看视频教程
               
              
              [weakSelf LookVideo];
          }];
         
}
- (void)initUI:(NSDictionary *)dic
{
    NSString * shareInfo = dic[@"shareInfo"];
    
//    NSString *shareStr = [shareInfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSData *shareData = [shareInfo dataUsingEncoding:NSUnicodeStringEncoding];
    NSDictionary *shareOptions = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSMutableAttributedString *shareAttr = [[NSMutableAttributedString alloc] initWithData:shareData options:shareOptions documentAttributes:nil error:nil];
    [shareAttr addAttribute:NSFontAttributeName value:AutoFont(10) range:NSMakeRange(0, shareAttr.length)];
    CGSize shareAttSize = [shareAttr boundingRectWithSize:CGSizeMake(UIScreenWidth-30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    _shareLab.attributedText = shareAttr;
    _shareLab.height = shareAttSize.height;
    _commentButton.mj_y = _shareLab.bottom +10;
    
    NSString *str = [dic[@"commentInfo"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [str dataUsingEncoding:NSUnicodeStringEncoding];
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    [attr addAttribute:NSFontAttributeName value:AutoFont(10) range:NSMakeRange(0, attr.length)];
    CGSize attSize = [attr boundingRectWithSize:CGSizeMake(UIScreenWidth-32, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    _commentLab.attributedText = attr;
    _commentLab.height = attSize.height;
    _commentLab.mj_y = _commentButton.bottom+10;
    _imgBgView.mj_y = _commentLab.bottom +10;
    NSArray * images = dic[@"taskInfoImages"];
    for (int i=0; i<images.count; i++)
    {
        NSDictionary * dic = images[i];
        UIImageView * imageView = _images[i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:dic[@"url"]]];
    }
    _tableviewHeadView1.mj_y = _imgBgView.bottom;
     [_scrollerView setContentSize:CGSizeMake(UIScreenWidth, _shareLab.height+10+ _commentButton.height +10 +_commentLab.height+10 + _imgBgView.height + _tableviewHeadView1.height+60)];
    NSInteger isReceive = [dic[@"isReceive"] integerValue];
    _state = isReceive;
    _taskMoney = dic[@"taskMoney"];
    switch (isReceive) {//1=可领取 2=不可以 3=可提交 4=进行中 5=审核中  6=已完成 7=完成失败
        case 1:
            _tableviewHeadView1.subimtBtn.hidden = YES;
            _tableviewHeadView1.receiveBtn.hidden = NO;
            break;
        case 2:
            _tableviewHeadView1.subimtBtn.hidden =NO;
            _tableviewHeadView1.subimtBtn.userInteractionEnabled = NO;
            [_tableviewHeadView1.subimtBtn setTitle:@"已领取" forState:0];
            _tableviewHeadView1.subimtBtn.alpha = 0.5;
            _tableviewHeadView1.receiveBtn.hidden = YES;
            break;
        case 3:
            _tableviewHeadView1.subimtBtn.hidden =NO;
            _tableviewHeadView1.subimtBtn.userInteractionEnabled = YES;
            [_tableviewHeadView1.subimtBtn setTitle:@"可提交" forState:0];
            _tableviewHeadView1.subimtBtn.alpha = 1;
            _tableviewHeadView1.receiveBtn.hidden = YES;
            
            break;
        case 4:
            _tableviewHeadView1.subimtBtn.hidden =NO;
            _tableviewHeadView1.subimtBtn.userInteractionEnabled = NO;
            [_tableviewHeadView1.subimtBtn setTitle:@"进行中" forState:0];
            _tableviewHeadView1.subimtBtn.alpha = 0.5;
            _tableviewHeadView1.receiveBtn.hidden = YES;
            break;
        case 5:
            _tableviewHeadView1.subimtBtn.hidden =NO;
            _tableviewHeadView1.subimtBtn.userInteractionEnabled = NO;
            [_tableviewHeadView1.subimtBtn setTitle:@"审核中" forState:0];
            _tableviewHeadView1.subimtBtn.alpha = 0.5;
            _tableviewHeadView1.receiveBtn.hidden = YES;
            break;
        case 6:
            _tableviewHeadView1.subimtBtn.hidden =NO;
            _tableviewHeadView1.subimtBtn.userInteractionEnabled = NO;
            [_tableviewHeadView1.subimtBtn setTitle:@"已完成" forState:0];
            _tableviewHeadView1.subimtBtn.alpha = 0.5;
            _tableviewHeadView1.receiveBtn.hidden = YES;
            break;
        case 7:
            _tableviewHeadView1.subimtBtn.hidden =NO;
            _tableviewHeadView1.subimtBtn.userInteractionEnabled = NO;
            [_tableviewHeadView1.subimtBtn setTitle:@"任务失败" forState:0];
            _tableviewHeadView1.subimtBtn.alpha = 0.5;
            _tableviewHeadView1.receiveBtn.hidden = YES;
            break;
        default:
            break;
    }
    _scrollerView.hidden = NO;
    [self stopLoadingAnimation];
}
- (void)getTaskInfoById
{
    [self showLoadingAnimation];
      WeakSelf
      NSString  * getTaskInfoById = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getTaskInfoById"];
     [[SmileHttpTool sharedInstance] POST:getTaskInfoById parameters:@{@"id":_id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {

          NSDictionary * dic = responseObject[@"data"];
          if (!kDictIsEmpty(dic)) {
              self.taskInfoDicc  = [NSDictionary dictionaryWithDictionary:dic];
              [self initUI:dic];
          }else
          {
              [JMNotifyView showNotify:message isSuccessful:NO];
              [weakSelf stopLoadingAnimation];
          }
          
    } failure:^(id responseObject, NSError *error) {
           [weakSelf stopLoadingAnimation];
        
      }];
}
#pragma 查看视频
- (void)LookVideo
{
    LLWebViewController *webV = [LLWebViewController new];
    NSString * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"release"];
    webV.urlStr = url;
    webV.isPullRefresh = YES;
    [self.navigationController pushViewController:webV animated:YES];
}
#pragma 判断用户状态
- (void)buttonClick:(NSInteger)tag
{
    if (![ZBDUnit getLoginJurisdiction]) {
        return;
    }
    switch (tag) {
        case 1://领取任务
        {
            [self userReceiveTaskInfo];
            
        }
            break;
            
        case 2://提交任务
        {
            [self userSubmitTaskInfo];
        }
            break;
        case 3://复制分享语
        {
            if (_state==1) {
                [JMNotifyView showNotify:@"请先领取任务" isSuccessful:NO];
            }else
            {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = _shareLab.text;
                [JMNotifyView showNotify:@"已复制到粘贴板" isSuccessful:NO];
            }
             
        }
            break;
        case 4://复制评论语
        {
            if (_state==1) {
                 [JMNotifyView showNotify:@"请先领取任务" isSuccessful:NO];
            }else
            {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = _commentLab.text;
                [JMNotifyView showNotify:@"已复制到粘贴板" isSuccessful:NO];
            }
            
        }
            break;
        case 5://保存图片
        {
            if (_state==1) {
                 [JMNotifyView showNotify:@"请先领取任务" isSuccessful:NO];
            }else
            {
                [self getCode];//获取水印
                
            }
        }
            break;
            
        default:
            break;
    }
}
/*获取水印信息*/
- (void)getCode
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * getCode = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getCode"];
    [[SmileHttpTool sharedInstance] POST:getCode parameters:@{} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        
        if (statusCode==0) {
            NSInteger  number = [responseObject[@"number"] integerValue];
            if (number>0) {
                UIImageView * imageView = weakSelf.images[number-1];
                UIImage *newImage = [self yp_getNewImageWithOriginalImage:imageView.image   waterString:responseObject[@"code"]];
                imageView.image = newImage;
                for (int i=0; i< weakSelf.images.count; i++)
                {
                    UIImageView * imageView =  weakSelf.images[weakSelf.images.count -i-1];
                    UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
                }
                 [JMNotifyView showNotify:@"成功保存到相册" isSuccessful:NO];
                
            }else
            {
                for (int i=0; i< weakSelf.images.count; i++)
                {
                    UIImageView * imageView =  weakSelf.images[weakSelf.images.count -i-1];
                    UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
                }
                 [JMNotifyView showNotify:@"成功保存到相册" isSuccessful:NO];
                
            }
            
          
        }else
        {
             [JMNotifyView showNotify:message isSuccessful:NO];
        }
        [weakSelf stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopLoadingAnimation];
        
    }];
}
////使用方式
/**  根据需要打入水印的图片和文字，重新返回绘制结束后的新的图片*/
/**  waterImage:打入水印的图片，即为 如来 */
/**  waterString:打入水印的文字，即为"致敬经典" */
- (UIImage *)yp_getNewImageWithOriginalImage:(UIImage *)originalImage   waterString:(NSString *)waterString {

    UIGraphicsBeginImageContext(originalImage.size);
    
    // 原始图片渲染
    [originalImage drawInRect:CGRectMake(0, 0, originalImage.size.width, originalImage.size.height)];
    // 打入的水印的文字渲 染
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    
    paragraphStyle.alignment = NSTextAlignmentRight;
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    NSDictionary * dic = @{
        NSFontAttributeName : [UIFont systemFontOfSize:40],
        NSParagraphStyleAttributeName : paragraphStyle,
        NSForegroundColorAttributeName : [UIColor blackColor]
    };
    [waterString drawInRect:CGRectMake(0, originalImage.size.height-60,  originalImage.size.width, 50) withAttributes:dic];
    
    // 打入的水印的文字渲 染
    NSMutableParagraphStyle * topparagraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    
    topparagraphStyle.alignment = NSTextAlignmentLeft;
    topparagraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    NSDictionary * topdic = @{
        NSFontAttributeName : [UIFont systemFontOfSize:40],
        NSParagraphStyleAttributeName : topparagraphStyle,
        NSForegroundColorAttributeName : [UIColor whiteColor]
    };
    [waterString drawInRect:CGRectMake(0, 10,  originalImage.size.width, 50) withAttributes:topdic];
    
    UIGraphicsEndPDFContext();
    
    // UIImage
    UIImage * imageNew = UIGraphicsGetImageFromCurrentImageContext();
    
    return imageNew;
}
#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo
{
    NSString*message =@"";
    
    if(!error) {
        
    }else
        
    {
        
        message = [error description];
        [ZBDUnit showMessage:@"请在iPhone的\"设置-隐私-麦克风\"中允许访问麦克风"];
    }
    
}
#pragma 领取任务
- (void)userReceiveTaskInfo
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * userReceiveTaskInfo = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userReceiveTaskInfo"];
    [[SmileHttpTool sharedInstance] POST:userReceiveTaskInfo parameters:@{@"id":_id} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        
        if (statusCode==0) {
            ZDBReceiveCustomAlearView * custom = [[ZDBReceiveCustomAlearView alloc] initWithtiprice:kFormat(@"%@元",weakSelf.taskMoney)];
            [custom showLXAlertView];
            
            if (self.taskSuccess) {
                self.taskSuccess();
            }
            weakSelf.state =5;
            weakSelf.tableviewHeadView1.receiveBtn.hidden = YES;
        }else if (statusCode==9)
        {
           __block ZDBCustomerAlearView * custom = [[ZDBCustomerAlearView alloc] initWithtititle:@"温馨提示" content:@"你还未通过资料审核\n请上传软件相关截图完成资料审核" cancel:@"稍后处理" submit:@"提交资料"];
                  [custom showLXAlertView];
                  WeakSelf
                  [custom.submitBtn add_BtnClickHandler:^(NSInteger tag) {
                      [custom dismissAlertView];
                      ZDBBindWXViewController *bindWXVC = [[ZDBBindWXViewController alloc] init];
                      [weakSelf.navigationController pushViewController:bindWXVC animated:YES];
                      
                  }];
            
        }else if (statusCode==2)
        {
            __block ZDBCustomerAlearView * custom = [[ZDBCustomerAlearView alloc] initWithtititle:@"温馨提示" content:message cancel:@"稍后处理" submit:@"重新提交"];
            [custom showLXAlertView];
            WeakSelf
            [custom.submitBtn add_BtnClickHandler:^(NSInteger tag) {
                [custom dismissAlertView];
                ZDBBindWXViewController *bindWXVC = [[ZDBBindWXViewController alloc] init];
                [weakSelf.navigationController pushViewController:bindWXVC animated:YES];

            }];
            
        }else
        {
             [JMNotifyView showNotify:message isSuccessful:NO];
        }
        [weakSelf stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopLoadingAnimation];
        
    }];
}
#pragma 提交任务
- (void)userSubmitTaskInfo
{
//     [self showLoadingAnimation];
//       WeakSelf
//       NSString  * userSubmitTaskInfo = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userSubmitTaskInfo"];
//       [[SmileHttpTool sharedInstance] POST:userSubmitTaskInfo parameters:@{@"id":_id} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
//
//           if (statusCode==0) {
//
//               if (self.taskSuccess) {
//                   self.taskSuccess();
//               }
//            weakSelf.tableviewHeadView1.subimtBtn.hidden = YES;
//              [JMNotifyView showNotify:@"任务已提交" isSuccessful:NO];
//           }else
//           {
//               [JMNotifyView showNotify:message isSuccessful:NO];
//
//           }
//           [weakSelf stopLoadingAnimation];
//
//       } failure:^(id responseObject, NSError *error) {
//           [weakSelf stopLoadingAnimation];
//
//       }];
    
    ZDBTastModel * model = [ZDBTastModel new];
    model.title = [self.taskInfoDicc jsonString:@"taskTitle"];
    model.taskUrl = [self.taskInfoDicc jsonString:@"taskUrl"];
    
    model.money = [self.taskInfoDicc jsonString:@"taskMoney"];
    //1=可领取 2=不可以 3=可提交 4=进行中 5=审核中 6=已完成 7=完成失败
    ////任务状态 1=进行中 2=审核中 3=已完成 4=已过期
    model.tiid = [self.taskInfoDicc jsonString:@"id"];
    model.integral = [self.taskInfoDicc jsonString:@"taskIntegral"];
    //model.state = [self.taskInfoDicc jsonString:@"state"];
    
    if ([self.taskInfoDicc jsonInteger:@"state"] ==3 ||[self.taskInfoDicc jsonInteger:@"state"] ==4 ) {
        model.state = @"1";
    }else if ([self.taskInfoDicc jsonInteger:@"state"] ==5){
        model.state = @"2";
    }else if ([self.taskInfoDicc jsonInteger:@"state"] ==6){
        model.state = @"3";
    }else{
        model.state = @"1";
    }
    
    
    
    
    ZDBSubimtTaskViewController *subimtTaskVC = [[ZDBSubimtTaskViewController alloc] init];
         subimtTaskVC.title = @"提交任务";
         subimtTaskVC.model = model;
         subimtTaskVC.id = model.tiid;
         [self.navigationController pushViewController:subimtTaskVC animated:YES];
         WeakSelf
         subimtTaskVC.updetaTaskBlock = ^(BOOL isUpdate) {
             [weakSelf getTaskInfoById];
         };
    
    
//    @property (nonatomic,strong)NSString * receiveTime;//领取时间
//    @property (nonatomic,strong)NSString * title;
//    @property (nonatomic,strong)NSString * taskUrl;
//    @property (nonatomic,strong)NSString * state;//任务状态 1=进行中 2=审核中 3=已完成 4=已过期
//    @property (nonatomic,strong)NSString * money;//金额
//    @property (nonatomic,strong)NSString * tiid;//
//    @property (nonatomic,strong)NSString * integral;//积分
    
    
    
}
- (UIScrollView *)scrollerView
{
    if (!_scrollerView) {
        _scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 60, UIScreenWidth, UIScreenHeight -kStatusBarAndNavigationBarHeight-60)];
        _scrollerView.backgroundColor = CLEARCOLOR;
        _scrollerView.showsVerticalScrollIndicator = NO;
        _scrollerView.showsHorizontalScrollIndicator = NO;
        _scrollerView.hidden = YES;
    }
    return _scrollerView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
